import 'dart:async';
import 'dart:io';

String localFile(path) {
  return Platform.script.resolve(path).toFilePath();
}

SecurityContext serverContext = new SecurityContext()
  ..useCertificateChain(localFile('../certificates/server_chain2.pem'))
  ..usePrivateKey(localFile('../certificates/server_key2.pem'),
      password: 'dartdart');

void main() async {
  var secure = true;
  var HOST_NAME = '127.0.0.1';
  Future<HttpServer> createServer({int backlog: 0}) => secure
      ? HttpServer.bindSecure(HOST_NAME, 44444, serverContext, backlog: backlog)
      : HttpServer.bind(HOST_NAME, 33333, backlog: backlog);
  var completer = Completer();
  try {
    var server = await createServer();
    await server.transform(WebSocketTransformer()).listen((socket) {
      print('收到新连接...');
      socket.listen((data) {
        print('$data');
        socket.add(data);
      }, onDone: () {
        print('done');
      }, onError: (error) {
        print('$error');
      });
    });
    print('server.address: ${server.address.host}');
    print('server.port: ${server.port}');
    print('${secure ? "wss" : "ws"}://${server.address.host}:${server.port}');
  } catch (e) {
    print('$e');
    completer.complete();
  }
  return completer.future;
}
